

import 'package:barcode_scan/barcode_scan.dart';
import 'package:erp/Entity/Customer.dart';
import 'package:erp/Entity/Product.dart';
import 'package:erp/Entity/ProductDetailAtPurchaseOrSell.dart';
import 'package:erp/Entity/ProductInWareHouse.dart';
import 'package:erp/Entity/SalesOrder.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Extensions/DateTime.dart';
import 'package:erp/Store/AccountStore.dart';
import 'package:erp/Store/ProductStore.dart';
import 'package:erp/UI/CodeResources/Localization.dart';
import 'package:erp/UI/Components/EmbeddableStatefulWidget.dart';
import 'package:erp/UI/Components/EventfulState.dart';
import 'package:erp/UI/Components/LogoScaffold.dart';
import 'package:erp/UI/Components/MessageDialog.dart';
import 'package:erp/UI/Pages/BasicInformationManagementPages/CustomerPages/CustomerPage.dart';
import 'package:erp/UI/Pages/BasicInformationManagementPages/ProductManagementPages/ProductInfoManagement.dart';
import 'package:erp/UI/Pages/WareHouseManagement/WareHouseManagementPage.dart';
import 'package:erp/global.dart';
import 'package:flutter/material.dart';

class SalesPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => SalesPageState();
}

class SalesPageState extends EventfulState<SalesPage> {
  var customerPanelExpanded = false;
  var productPanelExpanded = false;
  Customer selectedCustomer;
  List<ProductDetailAtPurchaseOrSell> selectedProducts = [];

  @override
  void initState() {
    eventIds = [
      globalBus.subscribe(Events.SALES_ORDER_INSERT_ERROR, (bus, error) async {
        await showMessageDialog(context, title: "سىتىشتا خاتالىق كۆرۈلدى", content: error.toString());
      }),
      globalBus.subscribe(Events.SALES_ORDER_INSERT_SUCCESS, (bus, data){
        Navigator.of(context).pop();
      })
    ];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return LogoScaffold(
      heroName: "FloatingActionButton",
      title: "سىتىش",
      assetsLogoName: "assets/pictures/cells.png",
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.save),
        onPressed: (){
          var order = SalesOrder();
          order.products = selectedProducts;
          showConfirmDialog(order);
        }
      ),
      contentDelegate: SliverChildListDelegate([
        Padding(
          padding: EdgeInsets.all(15.0),
          child: ExpansionPanelList(
            expansionCallback: (index, expanded){
              setState(() {
                if (index == 0)
                  customerPanelExpanded = !expanded;
                if (index == 1) productPanelExpanded = !expanded;
              });
            },
            children: [
              ExpansionPanel(
                headerBuilder: (context, expanded) => Padding(
                  padding: EdgeInsets.symmetric(horizontal: 15.0),
                  child: Row(
                    children: <Widget>[
                      Text("خىرىدار تاللاي"),
                      Switch(value: customerPanelExpanded, onChanged: (value){
                        setState(() {
                          customerPanelExpanded = value;
                        });
                      })
                    ],
                  ),
                ),
                body: Padding(
                  padding: EdgeInsets.all(15.0),
                  child: Column(
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          Expanded(
                            child: Text("خىرىدار"),
                          ),
                          RaisedButton(child: Text(selectedCustomer?.name ?? "چىكىپ خىرىدار تاللاڭ"), onPressed: () async {
                            selectedCustomer = await Navigator.of(context).push(MaterialPageRoute(builder: (context) => CustomerPage(isSelectionMode: true,)));
                            if (selectedCustomer != null) setState(() {});
                          },)
                        ],
                      ),
                    ],
                  )
                ),
                isExpanded: customerPanelExpanded
              ),
              ExpansionPanel(
                headerBuilder: (context, expanded) => Padding(
                  padding: EdgeInsets.symmetric(horizontal: 15.0),
                  child: Align(
                    alignment: Alignment(1.0, 0.0),
                    child: Text("ساتماقچى بولغان تاۋارلار"),
                  )
                ),
                body: Column(
                  children: <Widget>[
                    Column(
                      children: selectedProducts.map((product) => buildProductListItem(product)).toList()
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        FlatButton(
                            child: Icon(Icons.add),
                            onPressed: () async {
                              var product = await Navigator.of(context).push<ProductInWareHouse>(MaterialPageRoute(builder: (context) => WareHouseManagementPage(isSelectionMode: true, title: "ساتماقچى بولغان تاۋارنى تاللاڭ",)));
                              if (product != null) productSelected(product);
                            }
                        ),
                        FlatButton(
                            child: Icon(Icons.camera_enhance),
//                            onPressed: () async {
//                              var barCode = await BarcodeScanner.scan();
//                              if (barCode != null){
//                                var product = ProductStore.products.singleWhere((product) => product.barCode == barCode, orElse: () => null);
//                                if (product != null) productSelected(product);
//                              }
//                            }
                        ),
                      ],
                    )
                  ],
                ),
                isExpanded: productPanelExpanded
              )
            ],
          )
        ),
        SizedBox(
          height: 100.0,
        )
      ]),
    );
  }

  Widget buildProductListItem(ProductDetailAtPurchaseOrSell product){
    return ListTile(
      title: Text(product.nameUg),
      subtitle: Text(product.count.toString()),
      leading: Image.asset("assets/pictures/boxes.png", width: 40.0, height: 40.0,),
      trailing: Wrap(
        children: <Widget>[
          IconButton(
            icon: Icon(Icons.edit),
            onPressed: () async{
              await fillParameterDialog(context, product);
              setState(() {});
            },
          ),
          IconButton(
            icon: Icon(Icons.delete_forever),
            onPressed: (){
              setState(() {
                selectedProducts.removeWhere((item) => item.productCode == product.productCode);
              });
            },
          ),
        ],
      ),
    );
  }

  void productSelected(ProductInWareHouse product) async {
    var newProduct = ProductDetailAtPurchaseOrSell.fromProductInWareHouse(product);
    if (!(await fillParameterDialog(context, newProduct)) ?? false) return;

    var oldProduct = selectedProducts.singleWhere((item) => item.productCode == newProduct.productCode , orElse: () => null);
    if (oldProduct == null){
      oldProduct = newProduct;
      selectedProducts.add(oldProduct);
    }
    else oldProduct.count += newProduct.count;
    setState(() {});
  }

  Future<bool> fillParameterDialog(BuildContext context, ProductDetailAtPurchaseOrSell product) async {
    var currentLocale = AppLocalizations.of(context);
    var countFieldController = TextEditingController(text: product.count?.toString() ?? "");
    var priceFieldController = TextEditingController(text: product.sellPrice?.toString() ?? "");

    return await showDialog(context: context, barrierDismissible: false, builder: (context) => Directionality(
      textDirection: currentLocale.textDirection,
      child: AlertDialog(
        title: Text(product.nameUg),
        content: Wrap(
          children: <Widget>[
            TextField(
              controller: countFieldController,
              decoration: InputDecoration(
                labelText: "مىقدارىنى كىرگۈزۈڭ",
                hintText: "مەسىلەن كىلوگىرام، دانە، قۇتا... دىگەندەك",
              ),
              keyboardType: TextInputType.numberWithOptions(decimal: true, signed: false),
            ),
            TextField(
              controller: priceFieldController,
              decoration: InputDecoration(
                labelText: "سىتىش باھاسى",
                hintText: "سىتىش باھاسىنى كىرگۈزۈڭ"
              ),
              keyboardType: TextInputType.numberWithOptions(decimal: true, signed: false),
            ),
          ],
        ),
        actions: <Widget>[
          FlatButton(
            child: Text("جەزىملەشتۈرۈش"),
            onPressed: (){
              var count = 0.0;
              var price = 0.0;
              var showMessage = (){
                showMessageDialog(context, title: "ئەسكەرتىش", content: "مىقدارى ۋە باھاسىنى تولۇق كىرگۈزۈڭ");
              };
              try {
                count = num.tryParse(countFieldController.text).toDouble();
                price = num.tryParse(priceFieldController.text).toDouble();
              }
              catch (exception){
                showMessage();
                return;
              }
              var valid = count > 0 && price > 0;
              if (!valid){
                showMessage();
                return;
              }
              product.count = count;
              product.sellPrice = price;
              Navigator.of(context).pop(true);
            },
          ),
          FlatButton(
            child: Text("بىكار قىلىش"),
            onPressed: (){
              Navigator.of(context).pop(false);
            },
          ),
        ],
      ),
    ));
  }

  Future<void> showConfirmDialog(SalesOrder order) async {
    order.amount = 0.0;
    order.products.forEach((item) => order.amount += item.sellPrice * item.count);
    bool onCredit = false;

    TextEditingController actualMoney = TextEditingController(text: order.amount.toString());

    await showDialog(context: context, barrierDismissible: false, builder: (context)=> Directionality(textDirection: TextDirection.rtl, child: EmbeddedWidget(
        initEvent: (state){

        },
        widgetBuilder: (context, state){
          return AlertDialog(
            title: Text("ھىساب ئۈزۈش"),
            content: Wrap(
              children: <Widget>[
                Padding(padding: EdgeInsets.all(0.0), child: AnimatedContainer(
                  duration: Duration(milliseconds: 300),
                  child: Column(children: <Widget>[
                    Row(children: <Widget>[
                      Text("ئومومى سوممىسى: "),
                      Text(order.amount.toString(),),
                    ],),
                    TextField(
                      decoration: InputDecoration(
                        hintText: "ئەمەلىي سومما",
                        labelText: "ئەمەلىي سوممىسى",
                      ),
                      keyboardType: TextInputType.numberWithOptions(signed: true, decimal: true),
                      controller: actualMoney,
                      onChanged: (text){
                        var number = num.parse(text).toDouble();
                        if (number >= order.amount)
                          state.setState(() {
                            onCredit = false;
                            if (number > order.amount)
                              actualMoney.text = order.amount.toString();
                          });
                        else
                          state.setState(() {
                            onCredit = true;
                          });
                      },
                    ),
                    SizedBox(height: 20.0,),

                    Visibility(
                      visible: onCredit,
                      child: Row(
                        children: <Widget>[
                          Expanded(child: Text("قەرىز قايتۇرۇش ۋاقتى")),
                          Text(toDate(order.repayDate)),
                          IconButton(icon: Icon(Icons.access_time), onPressed: () async {
                            var date = await showDatePicker(context: context, initialDate: DateTime.now().add(Duration(days: 1)), firstDate: DateTime.now(), lastDate: DateTime.now().add(Duration(days: 360 * 5)));
                            if (date != null) {
                              state.setState((){
                                order.repayDate = date;
                              });
                            }
                          },
                          )
                        ],
                      ),)
                  ],),
                ),)
              ],
            ),
            actions: <Widget>[
              FlatButton(child: Text("جەزىملەشتۈرۈش"), onPressed: (){

                try {
                  order.sAmount = num.parse(actualMoney.text).toDouble();
                }
                catch (exception){
                  showMessageDialog(context, title: "ئەسكەرتىش", content: "ئەمەلىي سوممىسىنى كىرگۈزۈڭ");
                  return;
                }

                if ((order.sAmount ?? 0.0) < order.amount && order.repayDate == null){
                  showMessageDialog(context, title: "ئەسكەرتىش", content: "قەرىز قايتۇرۇش ۋاقتىنى كىرگۈزۈڭ");
                  return;
                }

                if (order.products.length == 0){
                  showMessageDialog(context, title: "ئەسكەرتىش", content: "ئەكىرمەكچى بولغان تاۋارلارنى تاللاڭ");
                  return;
                }

                if (customerPanelExpanded && selectedCustomer == null){
                  showMessageDialog(context, title: "ئەسكەرتىش", content: "خىرىدار تاللاڭ");
                  return;
                }

                order.time = DateTime.now();
                order.employee = AccountStore.signInResult.id;
                order.employeeName = AccountStore.signInResult.name;
                if (selectedCustomer != null) order.customer = customerPanelExpanded ? selectedCustomer.id : 0;

                globalBus.publish(Events.SALES_ORDER_INSERT_REQUEST, order);
                Navigator.of(context).pop(null);
              }),
            ],
          );
        }
    )));
//    globalBus.publish(Events.PURCHASE_INSERT_REQUEST, order);
  }
}
